package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.mapper.CommodityMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ICommodityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommodityServiceImpl implements ICommodityService {

    @Autowired
    private CommodityMapper commodityMapper;

    @Override
    public PageInfo query(QueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(),queryObject.getPageSize());
        List<Commodity> commodities = commodityMapper.selectForList(queryObject);
        return new PageInfo(commodities);
    }

    @Override
    public void delete(Long id) {
        commodityMapper.deleteByPrimaryKey(id);
        commodityMapper.deleteRelation(id);
    }

    @Override
    public void saveOrUpdate(Commodity commodity) {
        if (commodity.getId()!=null){
            commodityMapper.updateByPrimaryKey(commodity);
            commodityMapper.updateRelation(commodity.getId(),commodity.getCommodityCatalog().getId());
        }else{
            try{
                commodityMapper.insert(commodity);
                commodityMapper.insertRelation(commodity.getId(),commodity.getCommodityCatalog().getId());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Commodity> list() {
        return commodityMapper.selectAll();
    }

    @Override
    public Commodity getById(Long id) {
        return commodityMapper.selectByPrimaryKey(id);
    }

    /**
     * 得到商品的价格
     * @param id
     * @return
     */
    @Override
    public Commodity selectByCommodityId(Long id) {
        return commodityMapper.selectByCommodityId(id);
    }

}
